//
//  ProjectListViewController.swift
//  mggz
//
//  Created by ShareAnimation on 2017/8/9.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import MJRefresh
class ProjectListViewController: BaseViewController {
    enum ProjectPrepareState {
        case noAction   //没有签入，也没签出
        case signedIn   //签入
        case signedOut  //签出
    }
    
    fileprivate var _tableView: UITableView!
    fileprivate var tableView: UITableView {
        get {
            if _tableView != nil {
                return _tableView
            }
            _tableView = UITableView()
            _tableView.delegate = self
            _tableView.dataSource = self
            _tableView.tableFooterView = UIView()
            self.tableView.rowHeight = UITableViewAutomaticDimension
            self.tableView.estimatedRowHeight = 150
            _tableView.register(ProjectCell.self, forCellReuseIdentifier: "\(ProjectCell.self)")
            
            _tableView.register(ProjectOtherCell.self, forCellReuseIdentifier: "\(ProjectOtherCell.self)")
            return _tableView
        }
    }
    
    var searchController: UISearchController = {
        let vc = UISearchController(searchResultsController:SearchProjectViewController())
        vc.searchBar.placeholder = "搜索"//search改搜索
        vc.searchBar.setValue("取消", forKey: "_cancelButtonText")//英文cancel改取消
        vc.view.backgroundColor = UIColor (red: 0.97, green: 0.97, blue: 0.97, alpha: 1.0)
        return vc
    }()
    
    //选中一个项目后，将这个项目对应的projectModel回调
    var confirmSelection: ((ProjectModel) -> Void)?
    
    fileprivate var projectLists: [ProjectModel] = []
    fileprivate var selectedCell: IndexPath?    //选中的cell的indexPath
    fileprivate var currentPage = 1
    
    //是否要引起第一选择的变化？除了签到主界面，其他度不会。
    //同时，如果能引起第一选择变化的页面，即签到主界面，也显示『调入申请』类型的项目
    var isChangeSelection = false
    
    /*当前项目的签入签出状态
     在签到主界面进入这个界面，需要切换项目的时候，需要判断当前项目的签入签出状态。
     noAction:表示当前项目没有签入签出。
     signedIn:表示当前项目的最后一条签到记录是签入
     signedOut:表示当前项目的最后一条签到记录是签出
     */
    var projectPreapred: ProjectPrepareState = .noAction
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        self.title = "选择项目"
        self.extendedLayoutIncludesOpaqueBars = true
        self.edgesForExtendedLayout = UIRectEdge.init(rawValue: 0)
      

//        if isChangeSelection {
//           self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "确认", style: .done, target: self, action: #selector(doRightAction))
//        }
//        else {
//            self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "", style: .done, target: nil, action: nil)
//        }
        
        
        

        let tableHeader = MJRefreshNormalHeader { [unowned self] in
            self.getData()
        }
        tableHeader?.stateLabel.isHidden = true
        self.tableView.mj_header = tableHeader
        
        let tableFooter = MJRefreshAutoNormalFooter { [unowned self] in
            self.getNextPage()
        }
        self.tableView.mj_footer = tableFooter

        self.setupViews()
        
//        self.showLoadingView()
//        self.getData()
        self.tableView.mj_header.beginRefreshing()
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        WWProgressHUD.dismiss()
    }
    
    func setupViews() {
        searchController.searchBar.delegate = self
        searchController.delegate = self
        searchController.searchResultsUpdater = self

        
        self.view.addSubview(tableView)
        self.tableView.snp.makeConstraints { (make) in
            make.left.bottom.right.equalTo(self.view)
            make.top.equalTo(self.view)
        }
        self.tableView.tableHeaderView = self.searchController.searchBar
    }
    
    func getData() {
        self.currentPage = 1 //重置下拉引起的变化
        
        let isShowApplying = self.isChangeSelection
        
        ProjectModel.projectList(pageIndex: self.currentPage, isShowApplying: isShowApplying) { (response) in
            if response.success {

                self.projectLists = response.value!
                for (index,item) in self.projectLists.enumerated() {
                    if item.isAppSelected {
                        self.selectedCell = IndexPath(row: index, section: 0)
                    }
                }
                self.tableView.reloadData()
            }
            else {
                WWError(response.message)
            }
            if self.tableView.mj_header.isRefreshing {
                self.tableView.mj_header.endRefreshing()
            }
            self.tableView.mj_footer.resetNoMoreData()
            self.hideLoadingView()
        }
    }

    func getNextPage() {
        if self.projectLists.count <= 25 {
            self.tableView.mj_footer.endRefreshingWithNoMoreData()
            return
        }
        self.currentPage += 1
        let isShowApplying = self.isChangeSelection
        
        ProjectModel.projectList(pageIndex: self.currentPage, isShowApplying: isShowApplying) { (response) in
            if response.success {
                if response.value!.count <= 0 {
                    self.tableView.mj_footer.endRefreshingWithNoMoreData()
                    return
                }
                
                self.projectLists += response.value!
                
                self.tableView.reloadData()
                self.tableView.mj_footer.endRefreshing()
            }
            else {
                WWError(response.message)
            }
        }
    }
    
    func doRightAction() {
        guard self.isChangeSelection else {
            return
        }
        
        if let indexPath = self.selectedCell {
            let model = self.projectLists[indexPath.row]
            ProjectModel.updateProjectInformation(workerId: model.demandBaseMigrantWorkerID!, completionHandler: { (response) in
                if response.success {
                    if let confirm = self.confirmSelection {
                        confirm(model)
                    }
                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: kNotificationSelectedProjectChanged), object: nil)
                    self.navigationController?.popViewController(animated: true)
                }
                else {
                    WWError(response.message)
                }
            })
        }
        else {
            WWError("没有选中任何项目")
        }
        
    }
    
     deinit {
       
    }
}

extension ProjectListViewController: UITableViewDelegate,UITableViewDataSource, UISearchBarDelegate,UISearchControllerDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.projectLists.count
    }
//
//    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
//        return 100 + 25
//    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let selecModel = self.projectLists[indexPath.row]
        
        if selecModel.isWorking {
        let cell = tableView.dequeueReusableCell(withIdentifier: "\(ProjectOtherCell.self)", for: indexPath) as! ProjectOtherCell
        cell.bind(self.projectLists[indexPath.row])
        if indexPath == self.selectedCell {
            cell.isCellSelected = true
        }
        else {
            cell.isCellSelected = false
        }
            
        cell.callInHandler = {
            cell.projectStatus = .inApply
        }
        return cell
        }
        let cell = tableView.dequeueReusableCell(withIdentifier: "\(ProjectCell.self)", for: indexPath) as! ProjectCell
        cell.bind(self.projectLists[indexPath.row])
        if indexPath == self.selectedCell {
            cell.isCellSelected = true
        }
        else {
            cell.isCellSelected = false
        }
        //        if cell.isCellSelected {
        //            self.selectedCell = indexPath
        //        }
        cell.callInHandler = {
            cell.projectStatus = .inApply
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let selecModel = self.projectLists[indexPath.row]
        if selecModel.isWorking {
            let cell = tableView.cellForRow(at: indexPath) as! ProjectOtherCell
            if self.isChangeSelection == false {
                if let selection = self.confirmSelection {
                    selection(self.projectLists[indexPath.row])
                }
        self.navigationController?.popViewController(animated: true)
                
            }
            else if cell.projectStatus != .onJob {
                //            WWInform("未在职的不能选择")
            }
            else {
                if self.selectedCell == indexPath {
                    //                cell.isCellSelected = false
                    //                self.selectedCell = nil
                }else{
                    let message: String
                    switch self.projectPreapred {
                    case .noAction,.signedIn:
                        message = "确定要切换在职项目吗？"
//                    case .signedIn:
//                        message = "你已在另外一个项目中签入，是否前往签出"
                    case .signedOut:
                        message = "确定要切换在职项目吗？项目地址不一样可能会导致您的轨迹异常！"
                    }
                    
                    let alertController = ETSimpleAlertController.init(message, okHandler: {[unowned self] in
                            cell.isCellSelected = true
                            if let lastIndexPath = self.selectedCell {
                                if let aCell = tableView.cellForRow(at: lastIndexPath) {
                                    let lastCell = aCell as! ProjectOtherCell
                                    lastCell.isCellSelected = false
                                }
                            }
                            self.selectedCell = indexPath
                            self.doRightAction()
                    })
                    self.present(alertController, animated: true, completion: nil)
                }
            }
            if cell.isCellSelected == true && self.isChangeSelection != false{
        self.navigationController?.popViewController(animated: true)
            }
            
        }else{
            let cell = tableView.cellForRow(at: indexPath) as! ProjectCell
            if self.isChangeSelection == false {
                if let selection = self.confirmSelection {
                    selection(self.projectLists[indexPath.row])
                }
                self.navigationController?.popViewController(animated: true)
            }
            else if cell.projectStatus != .onJob {
                //            WWInform("未在职的不能选择")
            }
            else {
                if self.selectedCell == indexPath {
                    //                cell.isCellSelected = false
                    //                self.selectedCell = nil
                }else{
                    let message: String
                    switch self.projectPreapred {
                    case .noAction,.signedIn:
                        message = "确定要切换在职项目吗？"
                    case .signedOut:
                        message = "确定要切换在职项目吗？项目地址不一样可能会导致您的轨迹异常！"
                    }
                    let alertController = ETSimpleAlertController.init(message, okHandler: {[unowned self] in
                            cell.isCellSelected = true
                            if let lastIndexPath = self.selectedCell {
                                if let aCell = tableView.cellForRow(at: lastIndexPath) {
                                    let lastCell = aCell as! ProjectCell
                                    lastCell.isCellSelected = false
                                }
                            }
                            self.selectedCell = indexPath
                            self.doRightAction()
                    })
                    self.present(alertController, animated: true, completion: nil)
                }
            }
            if cell.isCellSelected == true{
        self.navigationController?.popViewController(animated: true)
                
            }
        }
}
    
//    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
//
//        return searchController.searchBar
//    }
//    
//    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
//        return 40
//    }
    
    //MARK: UISearchBarDelegate
    //点击键盘的search按钮时调用
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        if let text = searchBar.text {
            if let vc = self.searchController.searchResultsController {
                let searchVC = vc as! SearchProjectViewController
                searchVC.searchAction(searchText: text, completion: {[unowned self](result) in
                    if let confirm = self.confirmSelection {
                        confirm(result)
                    }
                    self.navigationController?.popViewController(animated: true)
                })
            }
        }

    }

}

extension ProjectListViewController: UISearchResultsUpdating {
    func updateSearchResults(for searchController: UISearchController) {
        if let vc = self.searchController.searchResultsController {
            let searchVC = vc as! SearchProjectViewController
            searchVC.searchProjectLists = []
            searchVC.actionHandler()
        }
    }
}










